package es.mfp.practicos.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class DNIValidator implements ConstraintValidator<DNI, String> {

	public void initialize(DNI constraintAnnotation) {
		// nothing to do
	}

	public boolean isValid(String object, ConstraintValidatorContext constraintContext) {

		return isNIF(object) || isCIF(object);

	}

	private boolean isNIF(String object) {

		if (object == null)
			return true;

		String nif = object;

		if (nif.toUpperCase().startsWith("X") || nif.toUpperCase().startsWith("Y")
				|| nif.toUpperCase().startsWith("Z"))
			nif = nif.substring(1);

		Pattern nifPattern = Pattern
				.compile("(\\d{1,8})([TRWAGMYFPDXBNJZSQVHLCKEtrwagmyfpdxbnjzsqvhlcke])");
		Matcher m = nifPattern.matcher(nif);
		if (m.matches()) {
			String letra = m.group(2);
			// Extraer letra del NIF
			String letras = "TRWAGMYFPDXBNJZSQVHLCKE";
			int dni = Integer.parseInt(m.group(1));
			dni = dni % 23;
			String reference = letras.substring(dni, dni + 1);

			if (reference.equalsIgnoreCase(letra)) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	private boolean isCIF(String cif) {
		Pattern p2 = Pattern.compile("^[a-zA-Z]{1}[0-9]{8}$");
		Matcher m2 = p2.matcher(cif);
		return m2.matches();
	}
}